// 方法1需要直接对数组中的每一个元素进行判断
const myPromiseAll = function(pList) {
    if(!Array.isArray(pList)) {
        throw new TypeError('传入的pList要是数组')
    }
    let result = new Array(pList.length)
    let count = 0
    return new Promise((resolve, reject) => {
        pList.forEach((item, index) => {
            if(item instanceof Promise) {
                item.then(res => {
                    result[index] = res
                    count++
                    if(count === pList.length) {
                        resolve(result)
                    }
                }).catch(err => {
                    reject(err)
                })
            } else {
                result[index] = res
                if(result.length === pList.length) {
                    resolve(result)
                }
            }
        })
    })
}
// 方法2 利用Promise.resolve这个方法对promise实例包装幂等性的特性
const myPromiseAll1 = function(pList) {
    if(!Array.isArray(pList)) {
        throw new TypeError('传入的pList要是数组')
    }
    let result = new Array(pList.length)
    return new Promise((resolve, reject) => {
        pList.forEach((item, index) => {
            Promise.resolve(item).then(res => {
                result[index] = res
                count++
                if(count === pList.length) {
                    return resolve(result)
                }
            }).catch(err => {
                return reject(err)
            })
        })
    })
}
let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('我是p1')
    }, 1000)
})
let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('我是p2')
    }, 3000)
})
let p3 = 10
// let p4 = new Promise((resolve, reject) => {
//     setTimeout(() => {
//         reject('我是p4')
//     }, 1000)
// })
let p4 = Promise.reject('rejected')
myPromiseAll1([p1, p2, p3, p4]).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
})